package com.app.reptile.tasks.selenium.video;

import com.app.reptile.constant.JobAnnotation;
import com.app.reptile.tasks.AbstractSeleniumV133Task;
import com.app.reptile.utils.BeanUtils;
import com.mybatis.mapper.CatUrlMapper;
import com.mybatis.mapper.CatVideoMapper;
import com.mybatis.pojo.CatUrl;
import com.mybatis.pojo.CatVideo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.htmlunit.WebClient;
import org.htmlunit.html.HtmlPage;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 每天中午23点触发
 */
@JobAnnotation("0 0 23 * * ?")
public class QiqiDm7Service extends AbstractSeleniumV133Task {
    public static void main(String[] args) {
        QiqiDm7Service service = new QiqiDm7Service();
        service.execute();
    }

    private CatVideoMapper catVideoMapper;

    private CatUrlMapper catUrlMapper;

    public CatUrlMapper getCatUrlMapper() {
        return catUrlMapper;
    }

    public void setCatUrlMapper(CatUrlMapper catUrlMapper) {
        this.catUrlMapper = catUrlMapper;
    }

    public CatVideoMapper getCatVideoMapper() {
        return catVideoMapper;
    }

    public void setCatVideoMapper(CatVideoMapper catVideoMapper) {
        this.catVideoMapper = catVideoMapper;
    }

    private File root = new File(ROOT,"video");

    private String baseUrl = "https://qiqidm7.com";


    @Override
    protected void start(ChromeDriver chromeDriver) throws Exception {
        WebClient webClient = BeanUtils.buildWebClient();
        HtmlPage htmlPage = webClient.getPage(baseUrl);
        String cxt = htmlPage.getWebResponse().getContentAsString();
        logger.info(cxt);
        Document document = Jsoup.parse(cxt);
        Elements elements = document.select("div.head ul.nav-pc li b.navb a");

        for (Element ele : elements){
            String title = ele.text();
            String text = ele.text();
            if ("首页".equals(title)){

            }
            if ("电视剧".equals(title)){
                String url = "https://qiqidm7.com/tv/0/0/all/1.html";
                parseTv_list(chromeDriver,title,url);
            }
            if ("电影".equals(title)){
                String url = "https://qiqidm7.com/mov/0/0/all/1.html";
                parseTv_list(chromeDriver,title,url);
            }
            if ("动漫".equals(title)){
                String url = "https://qiqidm7.com/acg/0/0/all/1.html";
                parseTv_list(chromeDriver,title,url);
            }
            if ("综艺".equals(title)){
                String url = "https://qiqidm7.com/zongyi/0/0/all/1.html";
                parseTv_list(chromeDriver,title,url);
            }
        }
    }


    private File createFile(String text){
        File file = new File(root,text);
        if (!file.exists()){
            file.mkdirs();
        }
        return file;
    }
    /**
     * tv 电视剧 四大分类
     * @param type
     * @param url
     */
    private void parseTv_list(ChromeDriver chromeDriver,String type,String url) throws InterruptedException {
        chromeDriver.get(url);
        Thread.sleep(5000);
        String pageSource = chromeDriver.getPageSource();
        Document document = Jsoup.parse(pageSource);
        Elements elements = document.select("div.scon dl");

        for (Element element : elements){
            Elements eles = element.select("a");
            for (Element e : eles){
                String text = e.text();
                if ("全部".equals(text)){
                    continue;
                }
                String href = e.attr("href");
                parseTv_list_next(chromeDriver,text,href,type);
            }
        }

    }

    /**
     * 解析每一页的数据
     * @param chromeDriver
     * @param type
     * @param href
     * @throws InterruptedException
     */
    private void parseTv_list_next(ChromeDriver chromeDriver,String lx,String href,String type) throws InterruptedException {
        File file = createFile(type);
        chromeDriver.get(baseUrl+href);
        Thread.sleep(5000);
        String pageSource = chromeDriver.getPageSource();
        Document document = Jsoup.parse(pageSource);
        Elements elements = document.select("div.index-tj ul.main li.mb");
        Elements eles = document.select("div.page a.a1");
        if (CollectionUtils.isNotEmpty(elements)){
            elements.forEach(element -> {
                Element a = element.getElementsByTag("a").first();
                String h = a.attr("href");
                String t = a.attr("title");
                Element img = element.selectFirst("div.img img.lazy");
                Element bz = element.selectFirst("div.img p.bz");

                //解析每个视频有多少集数
                chromeDriver.get(baseUrl+h);
                try {
                    Thread.sleep(3000);
                    String source = chromeDriver.getPageSource();
                    Document doc = Jsoup.parse(source);
                    Elements playList = doc.getElementById("play_list_34").select("li");
                    Elements tabList = doc.getElementById("stab_1_71").select("ul");

                    List<String> arr = playList.stream().filter(e->StringUtils.isNotBlank(e.text())).map(e-> e.text()).collect(Collectors.toList());
                    if (arr.size() > tabList.size()){
                        arr = arr.subList(1,arr.size());
                    }
                    for (int index = 0; index < tabList.size(); index ++){
                        if (index == 0){
                            continue;
                        }
                        Element tab = tabList.get(index);
                        Elements aList = tab.select("li a");
                        String tt = arr.get(index);
                        for (Element ele : aList){
                            String js = ele.attr("href");
                            String jsn = ele.text();
                            if (!js.startsWith("/")){
                                js = h +js;
                            }
                            //获取每一集的m3u8链接地址
                            chromeDriver.get(baseUrl+js);

                            WebDriverWait wait = new WebDriverWait(chromeDriver, Duration.ofSeconds(3));
                            // 切换到目标 iframe
                            wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("playiframe")));
                            // 直接操作 iframe 内的 DOM
                            WebElement divplay = chromeDriver.findElement(By.id("divplay"));
                            String s3= divplay.getDomProperty("outerHTML");
                            Document outerHTML = Jsoup.parse(s3);
                            String playUrl = outerHTML.getElementById("playiframe").attr("src");
                            String m3u8Url = playUrl.split("url=")[1];
                            String decoded = URLDecoder.decode(m3u8Url, StandardCharsets.UTF_8);
                            URL url = new URL(decoded);
                            System.out.println(url.toString());
                            CatUrl catUrl = new CatUrl();
                            catUrl.setUrl(decoded);
                            catUrl.setId(t);
                            catUrl.setStr1(jsn);
                            catUrl.setStr2(tt);

                            int cnt = catUrlMapper.selectByBeanCount(catUrl);
                            if (cnt == 0){
                                catUrlMapper.insert(catUrl);
                            }

                        }
                    }
                    CatVideo catVideo = new CatVideo();
                    catVideo.setTitle(t);
                    catVideo.setRemoteUrl(bz.text());
                    catVideo.setType("qiqidm7");
                    catVideo.setHashValue(type);
                    int cnt = catVideoMapper.selectBeanCount(catVideo);
                    if (cnt == 0){
                        catVideoMapper.insert(catVideo);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }else{
            return;
        }
        if (CollectionUtils.isNotEmpty(eles)){
            String url = eles.get(eles.size()-1).attr("href");
            parseTv_list_next(chromeDriver,lx,url,type);
        }
    }
}